package com.starblink.android.basic.network.interceptor

import com.apollographql.apollo3.api.ApolloRequest
import com.apollographql.apollo3.api.ApolloResponse
import com.apollographql.apollo3.api.Operation
import com.apollographql.apollo3.interceptor.ApolloInterceptor
import com.apollographql.apollo3.interceptor.ApolloInterceptorChain
import com.apollographql.apollo3.network.http.HttpInfo
import com.blankj.utilcode.util.LogUtils
import com.starblink.android.basic.network.base.BaseSiteSwitch
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.basic.storage.SkStorage
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.onEach

class CountryApolloInterceptor : ApolloInterceptor {
    override fun <D : Operation.Data> intercept(
        request: ApolloRequest<D>,
        chain: ApolloInterceptorChain
    ): Flow<ApolloResponse<D>> {
        return chain.proceed(request).onEach { response ->
            handleCountryCode(response)
        }

    }

    ///处理国家
    private fun <D : Operation.Data> handleCountryCode(
        response: ApolloResponse<D>
    ) {
        //https://www.apollographql.com/docs/kotlin/migration/3.0/#okhttp
        //HttpHeader(name=local_country, value=United Kingdom)
        //HttpHeader(name=local-country-code, value=GB)
        var needChange = false
        response.executionContext[HttpInfo]?.headers?.forEach {
            if (it.name == "local_country") {
                if (it.value != UserDataCenter.getLocalCountry()) {
                    needChange = true
                    UserDataCenter.putLocalCountry(it.value)
                }
            }
            if (it.name == "web-request-trace-id") {
                LogUtils.e("GuangApp", "----web-request-trace-id----->${it.value}")
            }
            if (it.name == "local-country-code") {
                if (it.value != UserDataCenter.getLocalCountryCode()) {
                    needChange = true
                    UserDataCenter.putLocalCountryCode(it.value)
                }
            }
        }
        //如果检测到国家变化了 那么改变header
        // 注销账户 提示重新登录
        if (needChange) {
            SkGqlClient.resetClient()
        }
    }


}